//
//  ZJSIRemarkView.m
//  ShangHaiHuDongApp
//
//  Created by ZJ on 2017/6/13.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJSIRemarkView.h"

@interface ZJSIRemarkView ()<LVRecordToolDelegate,ZJVoiceViewDelegate,UITextViewDelegate>
{
    UIView *_bgView;
}
/** 添加语音按钮 */
@property (nonatomic, strong) UIButton *addVoice;

/** 录音图片 */
@property (nonatomic, strong) UIImageView *imageView;
/** 播放视图 */
@property (nonatomic, strong) ZJVoiceView *voiceView;

@end

@implementation ZJSIRemarkView

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title
{
    self = [super initWithFrame:frame title:title];
    if (self) {
//        [self addSubview:self.addVoice];
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(self.titleLabel.x, self.titleLabel.bottom, self.width - 2 * self.titleLabel.x, self.height - self.titleLabel.bottom - 6 * [UIScreen zj_screenHScale])];
        _bgView.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        _bgView.layer.borderWidth = 1;
        _bgView.layer.borderColor = [UIColor zj_colorWithHexString:@"ebebeb"].CGColor;
        
        [self addSubview:_bgView];
        [self addSubview:self.textView];
        [self addSubview:self.voiceView];
        self.voiceView.hidden = YES;
//        self.recordTool = [LVRecordTool sharedRecordTool];
//        self.recordTool.delegate = self;
    }
    return self;
}



- (void)dealloc {
    
    if ([self.recordTool.recorder isRecording]){
        [self.recordTool stopPlaying];
    }
    if ([self.recordTool.player isPlaying]){
        [self.recordTool stopRecording];
    }
}
#pragma mark - 点击事件
// 按下
- (void)recordBtnDidTouchDown:(UIButton *)recordBtn {
    [[UIApplication sharedApplication].keyWindow addSubview:self.imageView];
    self.imageView.center = [self.imageView superview].center;
    [self.recordTool startRecording];
}

// 点击
- (void)recordBtnDidTouchUpInside:(UIButton *)recordBtn {
    [self.imageView removeFromSuperview];
    double currentTime = self.recordTool.recorder.currentTime;
    NSLog(@"%lf", currentTime);
    if (currentTime < 2) {
        
        self.imageView.image = [UIImage imageNamed:@"mic_0"];
        [self alertWithMessage:@"说话时间太短"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [self.recordTool stopRecording];
            [self.recordTool destructionRecordingFile];
        });
    } else {
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [self.recordTool stopRecording];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.imageView.image = [UIImage imageNamed:@"mic_0"];
            });
        });
        // 已成功录音
        self.voiceView.hidden = NO;
        
        self.voiceView.time = [NSString stringWithFormat:@"%ld",(NSInteger)currentTime];
        self.textView.height = self.voiceView.y - 6 * [UIScreen zj_screenHScale] - self.textView.y;
        
        NSData *data = [NSData dataWithContentsOfURL:self.recordTool.recordFileUrl];
        
        if (self.delegate) {
            [self.delegate ZJSIRemarkViewDelegate_RemarkSuccess:data];
        }
        
    }
}

#pragma mark - 弹窗提示
- (void)alertWithMessage:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

#pragma mark - LVRecordToolDelegate
- (void)recordTool:(LVRecordTool *)recordTool didstartRecoring:(int)no {
    
    NSString *imageName = [NSString stringWithFormat:@"V%d", no];
    self.imageView.image = [UIImage imageNamed:imageName];
}

#pragma mark - ZJVoiceViewDelegate 协议方法
- (void)ZJVoiceViewDelegate_deleteButtonClick{
    self.voiceView.hidden = YES;
    self.textView.height = _bgView.height - 24 * [UIScreen zj_screenHScale];
    
    [self.recordTool stopPlaying];
    [self.recordTool destructionRecordingFile];
    if (self.delegate) {
        [self.delegate ZJSIRemarkViewDelegate_RemarkSuccess:nil];
    }
}

- (void)ZJVoiceViewDelegate_PlayVoice{
   // 1.获取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"lvRecord.caf"];
    self.recordTool.recordFileUrl = [NSURL URLWithString:filePath];
    [self.recordTool playRecordingFile];
}


#pragma mark - Setter
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.textView resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    NSString * toBeString = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    if (toBeString.length >= self.maxNumber && range.length!= 1 && self.maxNumber > 0){
        textView.text = [toBeString substringToIndex:self.maxNumber];
        return NO;
        
    }
    return YES;
}


- (void)setIsShowMust:(BOOL)isShowMust{
    _isShowMust = isShowMust;
    if (isShowMust) {
        self.mustImageView.hidden = NO;
    }else{
        
        self.mustImageView.hidden = YES;
    }
    
}

#pragma mark - Getters
-  (UIButton *)addVoice{
    if (_addVoice == nil){
        _addVoice = [[UIButton alloc] initWithFrame:CGRectMake(self.width - (111 + 12) * [UIScreen zj_screenWScale], 5 * [UIScreen zj_screenHScale], 111 * [UIScreen zj_screenWScale], 30 * [UIScreen zj_screenHScale])];
        [_addVoice setTitle:@" 添加语音" forState:UIControlStateNormal];
        _addVoice.titleLabel.font = [UIFont titleTextFont];
        _addVoice.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        [_addVoice setImage:[UIImage imageNamed:@"voice_add"] forState:UIControlStateNormal];
        _addVoice.backgroundColor = [UIColor themeColor];
       
        // 录音按钮
        [_addVoice addTarget:self action:@selector(recordBtnDidTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_addVoice addTarget:self action:@selector(recordBtnDidTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _addVoice;
}

- (XXTextView *)textView{
    if (_textView == nil){
        _textView = [[XXTextView alloc] initWithFrame:CGRectMake(_bgView.x + 9 * [UIScreen zj_screenWScale], _bgView.y + 12 * [UIScreen zj_screenHScale], _bgView.width - 18 * [UIScreen zj_screenWScale], _bgView.height - 24 * [UIScreen zj_screenHScale])];
        _textView.textColor = [UIColor textBlackColor];
        _textView.font = [UIFont titleTextFont];
        _textView.xx_placeholder = @"请输入内容....";
        _textView.returnKeyType = UIKeyboardTypeTwitter;
        _textView.delegate = self;
    }
    return _textView;
}
- (UIImageView *)imageView{
    if (_imageView == nil){
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
        _imageView.contentMode = UIViewContentModeCenter;
    }
    return _imageView;
}

- (ZJVoiceView *)voiceView{
    if (_voiceView == nil){
        _voiceView = [[ZJVoiceView alloc] initWithFrame:CGRectMake(self.textView.x, _bgView.bottom - (12 + 30) * [UIScreen zj_screenHScale] , 120 * [UIScreen zj_screenWScale], 30 * [UIScreen zj_screenHScale])];
        _voiceView.delegate = self;
    }
    return _voiceView;
}

@end


@interface ZJVoiceView ()
/** imageView */
@property (nonatomic, strong) UIImageView *imageView;
/** label */
@property (nonatomic, strong) UILabel *label;

@end

@implementation ZJVoiceView

- (instancetype)initWithFrame:(CGRect)frame;
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.borderColor = [UIColor zj_colorWithHexString:@"c9c9c9"].CGColor;
        self.layer.borderWidth = 1;
        self.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_PlayVoice)];
        [self addGestureRecognizer:tapGest];
        [self addSubview:self.imageView];
        [self addSubview:self.label];
        [self addSubview:self.deleteButton];
        
    }
    return self;
}

- (void)actiob_delete{
    if (self.delegate) {
        [self.delegate ZJVoiceViewDelegate_deleteButtonClick];
    }
}
- (void)action_PlayVoice{
    if (self.delegate) {
        [self.delegate ZJVoiceViewDelegate_PlayVoice];
    }
}

#pragma mark - Setter
- (void)setTime:(NSString *)time{
    _time = time;
    self.label.text = [NSString stringWithFormat:@"%@''",time];
}

#pragma mark - Getters
- (UIImageView *)imageView{
    if (_imageView == nil){
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30 * [UIScreen zj_screenWScale], self.height)];
        _imageView.contentMode = UIViewContentModeCenter;
        _imageView.image = [UIImage imageNamed:@"voice_play"];
        
    }
    return _imageView;
}

- (UIButton *)deleteButton{
    if (_deleteButton == nil){
        _deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(self.width - self.imageView.width, 0, self.imageView.width, self.height)];
        [_deleteButton setImage:[UIImage imageNamed:@"voice_close"] forState:UIControlStateNormal];
        [_deleteButton addTarget:self action:@selector(actiob_delete) forControlEvents:UIControlEventTouchUpInside ];
    }
    return _deleteButton;
}
- (UILabel *)label{
    if (_label == nil){
        _label = [[UILabel  alloc] initWithFrame:CGRectMake(self.imageView.right, 0, self.deleteButton.x - self.imageView.right, self.height)];
        _label.textColor = [UIColor zj_colorWithHexString:@"a8a8a8"];
        _label.font = [UIFont titleTextFont];
    }
    return _label;
}
@end
